<template>
  <div class="classifyxq">
    <van-nav-bar
      title="商品分类"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    >
      <template #right>
        <van-icon name="search" size="18" @click="show = true" />
      </template>
    </van-nav-bar>
    <div class="scroll">
      <div class="scr-ct" v-if="goodsList.length">
        <my-card
          v-for="(item, index) in goodsList"
          :key="index"
          :itemObj="item"
        ></my-card>
      </div>
      <van-empty v-else description="暂无数据" />
    </div>
    <van-popup position="top" v-model:show="show">
      <van-search
        v-model="inputVal"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="show = false"
      />
      <div class="pop-ct">
        <p><span>历史记录</span><span style="color:red" @click="$store.commit('delAll')">全部删除</span></p>
        <van-tag v-for="(item,index) in history" closeable size="medium" type="primary" @click="onSearch(item)" @close="$store.commit('hisDel',index)" :key="index">&nbsp;{{item}}&nbsp;</van-tag>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { ref,computed } from "vue";
import myCard from "../../components/myCard";
import { getGoods } from "../../api/home/index.js";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
export default {
  components: { myCard },
  setup(props) {
    const { params } = useRoute();
    const { commit,state } = useStore();
    const history = computed(() => state.history);
    const goodsList = ref([]); // 所有的商品数据
    const show = ref(false);
    const inputVal = ref(""); // 搜索框的值
    const allGoods = ref([]); // 所有商品数据
    getGoods().then((res) => {
      goodsList.value = res.data.filter((item) => item.categoryId == params.id);
      allGoods.value = res.data;
    });
    const onSearch = (val) => {
      // 搜索事件
      // let arr = [{val:'1'},{val:'2'},{val:'3'},{val:'4'}]
      // console.log(arr.includes('4'));
      // includes 检验数组中是否包含某一项的时候，数组的项只能是基本数据类型
      goodsList.value = allGoods.value.filter((item) => item.name.includes(val));
      commit("saveHistory", val);
      inputVal.value = val;
      show.value = false;
    };
    return {
      goodsList,
      show,
      inputVal,
      onSearch,
      history
    };
  },
};
</script>

<style lang="scss" scoped>
.classifyxq {
  height: 100%;
}
.scroll {
  height: calc(100% - 46px);
  overflow: auto;
}
.scr-ct {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10px;
  box-sizing: border-box;
  justify-content: space-between;
}
.pop-ct{
  padding: 15px;
  box-sizing: border-box;
  font-size: 15px;
  p{
   display: flex;
   justify-content: space-between;
  }
  .van-tag{
    margin-top: 10px;
    margin-right: 10px;
  }
}
</style>
